package com.lt.integration.jpa.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.util.ArrayList;
import java.util.List;

/**
 * 装换工具类
 */
public class ConvertUtils {

	private static final ObjectMapper MAPPER = new ObjectMapper();

	static {
		MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		MAPPER.registerModule(new JavaTimeModule());
	}

	/**
	 * 对象装换
	 * @param obj
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T convert(Object obj, Class<T> clazz) {
		if (obj == null || clazz == null) {
			return null;
		}

		try {
			String json = MAPPER.writeValueAsString(obj);
			return MAPPER.readValue(json, clazz);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			throw new RuntimeException("object convert exception");
		}
	}

	/**
	 * 对象转换
	 * @param objList
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> convert(List<?> objList, Class<T> clazz) {
		List<T> list = new ArrayList<T>();
		for (Object obj : objList) {
			list.add(convert(obj, clazz));
		}
		return list;
	}

}
